package com.yykj.hospital.server.service.impl;

import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.common.util.LocalObjectUtil;
import com.yykj.hospital.client.dto.HospitalDepartmentDTO;
import com.yykj.hospital.server.dto.HospitalCheckImportDTO;
import com.yykj.hospital.server.form.HospitalCheckForm;
import com.yykj.hospital.server.model.entity.*;
import com.yykj.hospital.server.model.repository.HospitalCheckRepository;
import com.yykj.hospital.server.service.HospitalCheckService;
import com.yykj.hospital.server.service.HospitalDoctorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class HospitalCheckServiceImpl implements HospitalCheckService {
    @Override
    public HospitalCheck editHospitalCheck(HospitalCheck check) {
        if (check.getHospitalId() == null || check.getHospitalId() <= 0) {
            throw new NormalException(ResultEnums.PARAM_ERROR);
        }
        HospitalCheck val;
        if (check.getId() != null && check.getId() > 0) {
            val = hospitalCheckRepository.findById(check.getId()).orElseThrow(() -> new NormalException(ResultEnums.NOT_EXIST));
            LocalObjectUtil.copyNullValue(check, val);
        } else {
            val = new HospitalCheck();
            BeanUtils.copyProperties(check, val);
        }
        val = hospitalCheckRepository.save(val);
        return val;
    }

    @Override
    public List<HospitalCheck> listHospitalCheck(HospitalCheckForm form) {
        return hospitalCheckRepository.findAll(new Specification<HospitalCheck>() {
            @Override
            public Predicate toPredicate(Root<HospitalCheck> root, CriteriaQuery<?> query, CriteriaBuilder builder) {

                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(builder.equal(root.get("hospitalId"), form.getHospitalId()));
                if (form.getDepId() != null && form.getDepId() > 0) {
                    predicateList.add(builder.equal(root.get("depId"), form.getDepId()));
                }
                if (!StringUtils.isEmpty(form.getKeyword())) {
                    predicateList.add(builder.like(root.get("name"), "%" + form.getKeyword() + "%"));
                }

                if (form.getType() != null) {
                    predicateList.add(builder.equal(root.get("type"), form.getType()));
                }

                Predicate[] predicates = new Predicate[predicateList.size()];
                return query.where(predicateList.toArray(predicates)).getRestriction();
            }
        });

    }

    @Override
    public void deleteHospitalCheck(Integer id) {
        hospitalCheckRepository.deleteById(id);
    }

    @Override
    public boolean checkHospitalCheckList(Integer hospitalId, ExcelImportResult<HospitalCheckImportDTO> result) {
        Map<String, HospitalDepartmentDTO> departmentDTOMap = hospitalDoctorService.getHospitalDepartmentDTOMap(hospitalId);
        //检查dep code
        Iterator<HospitalCheckImportDTO> iterator = result.getList().iterator();
        while (iterator.hasNext()) {
            HospitalCheckImportDTO dto = iterator.next();
            HospitalDepartmentDTO hospitalDepartmentDTO = departmentDTOMap.get(dto.getDepCode());
            if (hospitalDepartmentDTO == null || hospitalDepartmentDTO.getPid() == 0) {
                result.setVerifyFail(true);
                dto.setErrorMsg("depCode 不存在或者不是二级科室");
                iterator.remove();
                result.getFailList().add(dto);
            }
        }
        return result.getFailList().size() == 0;
    }

    @Override
    public void importCheckList(Integer hospitalId, List<HospitalCheckImportDTO> list) {
        Map<String, HospitalDepartmentDTO> map = null;

        for (HospitalCheckImportDTO dto : list) {
            HospitalCheck check = new HospitalCheck();
            BeanUtils.copyProperties(dto,check);
            check.setHospitalId(hospitalId);
            check.setPrice(new BigDecimal(dto.getPriceStr()));
            check.setStatus(true);

            if (map == null) {
                map = hospitalDoctorService.getHospitalDepartmentDTOMap(hospitalId);
            }
            HospitalDepartmentDTO departmentDTO = map.get(dto.getDepCode());
            check.setDepId(departmentDTO.getId());
            check.setDepName(departmentDTO.getName());
            for (String detailKey : map.keySet()) {
                if (map.get(detailKey).getId().equals(departmentDTO.getPid())) {
                    check.setDepDetailName(map.get(detailKey).getName() + "," + departmentDTO.getName());
                }
            }

            hospitalCheckRepository.save(check);
        }
    }

    private HospitalCheckRepository hospitalCheckRepository;

    private HospitalDoctorService hospitalDoctorService;

    @Autowired
    public void setHospitalCheckRepository(HospitalCheckRepository hospitalCheckRepository) {
        this.hospitalCheckRepository = hospitalCheckRepository;
    }
    @Autowired
    public void setHospitalDoctorService(HospitalDoctorService hospitalDoctorService) {
        this.hospitalDoctorService = hospitalDoctorService;
    }
}
